package com.aiyige.page.my.download.adapter;

import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Space;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.base.db.dao.DownloadFileDao;
import com.aiyige.base.db.dao.DownloadModelDao;
import com.aiyige.base.db.table.DownloadFile;
import com.aiyige.base.db.table.DownloadModel;
import com.aiyige.page.my.download.event.EventRefreshDownloadProgress;
import com.aiyige.page.my.download.util.DownloadUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.TimeUtils;
import com.aiyige.utils.widget.CommonBottomDialogFragment;
import com.aiyige.utils.widget.RoundCornerImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.j256.ormlite.stmt.UpdateBuilder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;

/**
 * Created by zhuyakun on 2017/11/30.
 */

public class DownloadModelAdapter extends BaseQuickAdapter<DownloadModel, BaseViewHolder> {
    CommonBottomDialogFragment moreDialog;
    FragmentActivity activity;
    EventBus eventBus;

    public DownloadModelAdapter(FragmentActivity activity) {
        super(new LinkedList<DownloadModel>());
        eventBus = EventBus.builder().build();
        this.activity = activity;
        moreDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.upload_file_delete_dialog)
                .viewIdList(R.id.deleteBtn, R.id.cancelBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.deleteBtn: {
                                DownloadModel downloadModel = getItem(position);
                                try {
                                    UpdateBuilder<DownloadModel, String> updateBuilder = DownloadModelDao.getDao().updateBuilder();
                                    updateBuilder.updateColumnValue(DownloadModel.CONTROL_OPTION_FIELD, downloadModel.getModelType() != DownloadUtil.MODEL_TYPE_LOCAL_VIDEO ? DownloadUtil.CONTROL_OPTION_DELETE : DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY);
                                    updateBuilder.where().eq(DownloadModel.ID_FIELD, downloadModel.getId());
                                    updateBuilder.update();
                                } catch (Exception e) {
                                    Timber.e("onViewClicked:" + Log.getStackTraceString(e));
                                }
                                try {
                                    UpdateBuilder<DownloadFile, Integer> updateBuilder = DownloadFileDao.getDao().updateBuilder();
                                    updateBuilder.updateColumnValue(DownloadModel.CONTROL_OPTION_FIELD, downloadModel.getModelType() != DownloadUtil.MODEL_TYPE_LOCAL_VIDEO ? DownloadUtil.CONTROL_OPTION_DELETE : DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY);
                                    updateBuilder.where().eq(DownloadFile.PARENT_ID_FIELD, downloadModel.getId());
                                    updateBuilder.update();
                                } catch (Exception e) {
                                    Timber.e("onViewClicked:" + Log.getStackTraceString(e));
                                }
                                remove(position);
                                break;
                            }
                        }
                    }
                })
                .build();
    }

    @Override
    protected BaseViewHolder onCreateDefViewHolder(ViewGroup parent, int viewType) {
        BaseViewHolder baseViewHolder = new ViewHolder(getItemView(R.layout.download_model_item, parent));
        return baseViewHolder;
    }

    @Override
    public void onViewAttachedToWindow(BaseViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        registerEventBus(holder);
    }


    @Override
    public void onViewDetachedFromWindow(BaseViewHolder holder) {
        unregisterEventBus(holder);
        super.onViewDetachedFromWindow(holder);
    }

    private void registerEventBus(BaseViewHolder holder) {
        try {
            if (!eventBus.isRegistered(holder)) {
                eventBus.register(holder);
            }
        } catch (Exception e) {
        }
    }

    private void unregisterEventBus(BaseViewHolder holder) {
        try {
            if (eventBus.isRegistered(holder)) {
                eventBus.unregister(holder);
            }
        } catch (Exception e) {
        }
    }

    public EventBus getEventBus() {
        return eventBus;
    }

    @Override
    protected void convert(BaseViewHolder helper, DownloadModel item) {
        ((ViewHolder) helper).bindData(item);
    }

    public class ViewHolder extends BaseViewHolder {
        @BindView(R.id.selectIv)
        ImageView selectIv;
        @BindView(R.id.selectLayout)
        FrameLayout selectLayout;
        @BindView(R.id.marginSpace)
        Space marginSpace;
        @BindView(R.id.coverIv)
        RoundCornerImageView coverIv;
        @BindView(R.id.statusIv)
        ImageView statusIv;
        @BindView(R.id.statusTv)
        TextView statusTv;
        @BindView(R.id.statusLayout)
        LinearLayout statusLayout;
        @BindView(R.id.coverLayout)
        FrameLayout coverLayout;
        @BindView(R.id.titleTv)
        TextView titleTv;
        @BindView(R.id.totalEpisodeTv)
        TextView totalEpisodeTv;
        @BindView(R.id.slashTv)
        TextView slashTv;
        @BindView(R.id.durationTv)
        TextView durationTv;
        @BindView(R.id.moreBtn)
        ImageView moreBtn;
        @BindView(R.id.playHistoryTv)
        TextView playHistoryTv;
        DownloadModel data;


        public ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        @Subscribe(threadMode = ThreadMode.MAIN)
        public void onEvent(EventRefreshDownloadProgress event) {
            bindData(data);
        }

        public void maybeRefresh(DownloadModel data) {
            try {
                DownloadModelDao.getDao().refresh(data);
                List<DownloadFile> downloadFileList = DownloadFileDao.getDao().queryBuilder()
                        .where()
                        .eq(DownloadFile.PARENT_ID_FIELD, data.getId())
                        .and()
                        .ne(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE)
                        .and()
                        .ne(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY)
                        .query();
                long totalDuration = 0;
                for (DownloadFile downloadFile : downloadFileList) {
                    totalDuration += downloadFile.getDuration();
                }
                data.setTotalDuration(totalDuration);
            } catch (Exception e) {
            }
        }


        @OnClick({R.id.moreBtn})
        public void onViewClick(View v) {
            switch (v.getId()) {
                case R.id.moreBtn:
                    moreDialog.setPosition(getAdapterPosition());
                    moreDialog.show(activity.getSupportFragmentManager(), "");
                    break;
            }
        }

        public void bindData(DownloadModel item) {
            data = item;
            maybeRefresh(data);
            if (data.getControlOption() == DownloadUtil.CONTROL_OPTION_DELETE || data.getControlOption() == DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY) {
                remove(getAdapterPosition());
                return;
            }
            if (data.getPlayIndex() < 0 && data.getPlayPosition() < 0) {
                playHistoryTv.setVisibility(View.INVISIBLE);
            } else {
                playHistoryTv.setVisibility(View.VISIBLE);
            }

            if (data.getModelType() == DownloadUtil.MODEL_TYPE_LEARN_VIDEO) {
                playHistoryTv.setText(StringUtils.getString(R.string.multi_video_play_history, String.valueOf(data.getPlayIndex() + 1), StringUtils.formatMediaDurationMS(data.getPlayPosition())));
            } else {
                playHistoryTv.setText(StringUtils.getString(R.string.single_video_play_history, StringUtils.formatMediaDurationMS(data.getPlayPosition())));
            }

            if (data.isEdit()) {
                selectLayout.setVisibility(View.VISIBLE);
                marginSpace.setVisibility(View.GONE);
            } else {
                selectLayout.setVisibility(View.GONE);
                marginSpace.setVisibility(View.VISIBLE);
            }

            if (data.isSelected()) {
                selectIv.setVisibility(View.VISIBLE);
            } else {
                selectIv.setVisibility(View.INVISIBLE);
            }
            titleTv.setText(Html.fromHtml(data.getTitle()));
            if (data.getModelType() == DownloadUtil.MODEL_TYPE_LEARN_VIDEO) {
                slashTv.setVisibility(View.VISIBLE);
                totalEpisodeTv.setVisibility(View.VISIBLE);
                totalEpisodeTv.setText(String.format(StringUtils.getString(R.string.total_episode), data.getMediaNum()));
            } else {
                slashTv.setVisibility(View.GONE);
                totalEpisodeTv.setVisibility(View.GONE);
            }
            durationTv.setText(StringUtils.formatMediaDurationMS(data.getTotalDuration()));
            switch (data.getProgressStatus()) {
                case DownloadUtil.PROGRESS_STATUS_WAITING_DOWNLOAD_COVER:
                case DownloadUtil.PROGRESS_STATUS_DOWNLOADING_COVER:
                case DownloadUtil.PROGRESS_STATUS_DOWNLOAD_COVER_FINISHED:
                case DownloadUtil.PROGRESS_STATUS_DOWNLOAD_COVER_FAILED:
                case DownloadUtil.PROGRESS_STATUS_WAITING_DOWNLOAD:
                case DownloadUtil.PROGRESS_STATUS_DOWNLOADING:
                case DownloadUtil.PROGRESS_STATUS_DOWNLOAD_FAILED:
                    statusLayout.setVisibility(View.VISIBLE);
                    break;
                case DownloadUtil.PROGRESS_STATUS_DOWNLOAD_FINISHED:
                    statusLayout.setVisibility(View.INVISIBLE);
                    break;
            }
            switch (data.getControlOption()) {
                case DownloadUtil.CONTROL_OPTION_DOWNLOAD:
                    statusIv.setImageResource(R.drawable.download);
                    statusTv.setText(R.string.downloading);
                    break;
                case DownloadUtil.CONTROL_OPTION_PAUSE:
                    statusIv.setImageResource(R.drawable.suspend);
                    statusTv.setText(R.string.pausing);
                    break;
            }

            switch (data.getProgressStatus()) {
                case DownloadUtil.PROGRESS_STATUS_WAITING_DOWNLOAD_COVER:
                case DownloadUtil.PROGRESS_STATUS_DOWNLOAD_COVER_FAILED:
                case DownloadUtil.PROGRESS_STATUS_DOWNLOADING_COVER:
                    Glide.with(itemView.getContext())
                            .load(data.getCoverRemoteUrl())
                            .apply(RequestOptions.placeholderOf(android.R.color.white))
                            .into(coverIv);
                    break;
                default:
                    Glide.with(itemView.getContext())
                            .load(data.getCoverLocalUrl())
                            .error(Glide.with(itemView.getContext())
                                    .load(data.getCoverRemoteUrl())
                                    .apply(RequestOptions.placeholderOf(android.R.color.white)))
                            .into(coverIv);
                    break;
            }
        }
    }

}
